﻿using System;
using System.CodeDom.Compiler;

namespace EmbeddedSharp.Core {
    public class CSharpFunctionCompiler {

        CodeDomProvider m_Provider = null;

        CompilerParameters m_CompilerParameters = null;

        public CSharpFunctionCompiler() {
            // Create the compiler
            m_Provider = new Microsoft.CSharp.CSharpCodeProvider();
            // Set the parameters of the compiler
            m_CompilerParameters = new CompilerParameters(
                new string[] { 
                    "System.dll",
                    this.GetType().Assembly.Location
                });
            m_CompilerParameters.GenerateInMemory = true;
            m_CompilerParameters.GenerateExecutable = false;
        }

        public IUnaryParameterFunction Parse(string expr) {
            //CheckExpression(ref expr);
            string src =
                "using System;using EmbeddedSharp.Core;"
                + "class myfunclass : IUnaryParameterFunction"
                + "{" + "public myfunclass(){}" + "public double Eval(double x)"
                + "{" + "return " + expr + ";" + "}" + "}";

            CompilerResults results = m_Provider.CompileAssemblyFromSource(
                m_CompilerParameters, src);
            if (results.Errors.Count == 0 && results.CompiledAssembly != null) {
                Type ObjType = results.CompiledAssembly.GetType("myfunclass");
                IUnaryParameterFunction func = null;

                if (ObjType != null) {
                    func = Activator.CreateInstance(ObjType) as IUnaryParameterFunction;
                }

                return func;
            } else throw new Exception(results.Errors[0].ToString());
        }
    }
}
